
#! /usr/bin/python

import sys
import os
import time
import random
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
     #   self.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1","type":"Italiano","Calle":"lacalle"}]


    def _process(self):
       pass
class MyCongregation(Organization.Congregation):
    pass

class MyTeam(Unit.Team):
    def onStart(self):
        self.auctioner=self.name+"@muc."+self.myAgent.getAID().getName().split("@")[1]+"/auctioner"
    def _process(self):
        if self.state=="available":
            goal=eval(self.getGoal())
            precio=goal["CurrentPrice"]
            comprador=goal["Buyer"]
            min=self.getMinAgents()
            agents=self.getNumberOfAgents()
            #print precio,comprador,min,agents
            if self.myAgent.dinero>precio+self.myAgent.incremento and comprador!=self.myAgent.getAID().getName() and min<=agents:
                #enviamos un mensaje con la nueva oferta
                mess=ACLMessage.ACLMessage()
                mess.setPerformative("inform")
                mess.setContent(str(precio+self.myAgent.incremento))
                #print mess
                self.sendPrivateMessage(mess,self.auctioner)
            mens=self.receiveMessage()
            if mens and "Sold" in mens.getContent():
                #print "The auction has finished: ",mens.getContent().split("Sold:")[1]
                self.leave()


"""
    def entryUnitTest(self,sender,desc=None):
      type=""
      subtype=""
      for l in desc:
          if l["name"]=="units":
              u=str(l["value"])
              u=int(u)
              self.unidades=self.unidades+u
              return self.entrada
      return False
"""

if __name__ == "__main__":
    a="comprador"
    if len(sys.argv)>1:
        max=sys.argv[1]
    else: max=5
    max=int(max)+1
    for n in xrange(1,max):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        b.start()
        b.dinero=random.randint(100,500)
        b.incremento=random.randint(1,10)
        continua=True
        while continua:
            try:
                list=b.getOrganizationList()
                for i in list:
                    #print i
                    info=b.getOrganizationInfo(i)
                    #print info
                    goal=info["goal"]
                    g=eval(goal)
                    if g.has_key("goal") and g["goal"]=="auction":
                        o=MyCongregation(b,nick=a+str(n), name=i)
                        b.joinOrganization(o)
                        l=o.getUnitList()
                        if l!=[]:
                            i=random.randint(0,len(l)-1)
                            b.producto=l[i]
                            print agent,b.dinero,b.incremento,b.producto
                            entry=o.requestEntryUnit(b.producto)
                            if entry:
                                u=MyTeam(b,nick=a+str(n), name=b.producto)
                                o.joinUnit(u)
                                continua=False
            except:
                pass







